#!/bin/bash
set -e

function mount_img {
	img_file="source_img/system.img"
	# error checks
	if [ ! -d source_img ] ; then
		echo "Error. No source_img folder found. You are running this script in an incorrect folder or you haven't unpacked your image yet (rkimg.sh)."
		exit 1
	fi
	if [ ! -f "${img_file}" ] ; then
		echo "Error. ${img_file} doesn't exist."
		exit 1
	fi

	mkdir -p system || true
	echo "****** Mounting ${img_file} to system/"
	sudo mount -o loop ${img_file} system/

	echo "****** Done."
	echo ""
	echo ""
}


function unmount_img {
	img_file="source_img/system.img"
	# error checks
	if [ ! -d source_img ] ; then
		echo "Error. No source_img folder found. You are running this script in an incorrect folder or you haven't unpacked your image yet (rkimg.sh)."
		exit 1
	fi
	if [ ! -f "${img_file}" ] ; then
		echo "Error. ${img_file} doesn't exist."
		exit 1
	fi

	echo "****** Fixing ownerships"
	sudo chown -R root:root system/app/

	echo "****** Fixing app permissions"
	sudo chmod 0644 system/app/*.apk

	echo "****** Fixing superuser permissions"
	foundsu=0
	if [ -e system/bin/su ]; then
		sudo chown root:2000 system/bin/su
		sudo chmod 6755 system/bin/su
		foundsu=1
	fi
	if [ -e system/xbin/su ]; then
		if [ $foundsu == 0 ]; then
			sudo chown root:2000 system/xbin/su
			sudo chmod 6755 system/xbin/su
		else
			echo "Duplicate su found (remove improper one):"
			ls -la system/bin/su
			ls -la system/xbin/su
		fi
	fi

	echo "****** Unmounting ${img_file}"
	sudo umount system/

	echo "****** Checking and optimizing system.img"
	e2fsck -fyD source_img/system.img

	echo "****** Done."
	echo ""
	echo ""
}

function usage {
	echo "Usage: ${0} -m	# to mount source_img/system.img"
	echo "       ${0} -u	# to unmount"
}



while getopts "mu" opt; do
	case $opt in
	m)
		mount_img
		exit 0
		;;
	u)
		unmount_img
		exit 0
		;;
	\?)
		echo "Error. Invalid option: ${OPTARG}" >&2
		usage
		exit 1
		;;
	esac
done

usage
